1   /*
2    * Copyright (C) 2010 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5    * in compliance with the License. You may obtain a copy of the License at
6    *
7    * http://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software distributed under the License
10   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11   * or implied. See the License for the specific language governing permissions and limitations under
12   * the License.
13   */
14  
15  package com.google.common.collect;
16  
17  import static com.google.common.base.Preconditions.checkArgument;
18  import static com.google.common.base.Preconditions.checkNotNull;
19  
20  import com.google.common.annotations.Beta;
21  import com.google.common.annotations.GwtCompatible;
22  
23  import java.util.NoSuchElementException;
24  
25  /**
26   * A sorted set of contiguous values in a given {@link DiscreteDomain}.
27   *
28   * <p><b>Warning:</b> Be extremely careful what you do with conceptually large instances (such as
29   * {@code ContiguousSet.create(Range.greaterThan(0), DiscreteDomain.integers()}). Certain
30   * operations on such a set can be performed efficiently, but others (such as {@link Set#hashCode}
31   * or {@link Collections#frequency}) can cause major performance problems.
32   *
33   * @author Gregory Kick
34   * @since 10.0
35   */
36  @Beta
37  @GwtCompatible(emulated = true)
38  @SuppressWarnings("rawtypes") // allow ungenerified Comparable types
39  public abstract class ContiguousSet<C extends Comparable> extends ImmutableSortedSet<C> {
40    /**
41     * Returns a {@code ContiguousSet} containing the same values in the given domain
42     * {@linkplain Range#contains contained} by the range.
43     *
44     * @throws IllegalArgumentException if neither range nor the domain has a lower bound, or if
45     *     neither has an upper bound
46     *
47     * @since 13.0
48     */
49    public static <C extends Comparable> ContiguousSet<C> create(
50        Range<C> range, DiscreteDomain<C> domain) {
51      checkNotNull(range);
52      checkNotNull(domain);
53      Range<C> effectiveRange = range;
54      try {
55        if (!range.hasLowerBound()) {
56          effectiveRange = effectiveRange.intersection(Range.atLeast(domain.minValue()));
57        }
58        if (!range.hasUpperBound()) {
59          effectiveRange = effectiveRange.intersection(Range.atMost(domain.maxValue()));
60        }
61      } catch (NoSuchElementException e) {
62        throw new IllegalArgumentException(e);
63      }
64  
65      // Per class spec, we are allowed to throw CCE if necessary
66      boolean empty = effectiveRange.isEmpty()
67          || Range.compareOrThrow(
68              range.lowerBound.leastValueAbove(domain),
69              range.upperBound.greatestValueBelow(domain)) > 0;
70  
71      return empty
72          ? new EmptyContiguousSet<C>(domain)
73          : new RegularContiguousSet<C>(effectiveRange, domain);
74    }
75  
76    final DiscreteDomain<C> domain;
77  
78    ContiguousSet(DiscreteDomain<C> domain) {
79      super(Ordering.natural());
80      this.domain = domain;
81    }
82  
83    @Override public ContiguousSet<C> headSet(C toElement) {
84      return headSetImpl(checkNotNull(toElement), false);
85    }
86  
87    @Override public ContiguousSet<C> subSet(C fromElement, C toElement) {
88      checkNotNull(fromElement);
89      checkNotNull(toElement);
90      checkArgument(comparator().compare(fromElement, toElement) <= 0);
91      return subSetImpl(fromElement, true, toElement, false);
92    }
93  
94    @Override public ContiguousSet<C> tailSet(C fromElement) {
95      return tailSetImpl(checkNotNull(fromElement), true);
96    }
97  
98    /*
99     * These methods perform most headSet, subSet, and tailSet logic, besides parameter validation.
100    */
101   /*@Override*/ abstract ContiguousSet<C> headSetImpl(C toElement, boolean inclusive);
102 
103   /*@Override*/ abstract ContiguousSet<C> subSetImpl(C fromElement, boolean fromInclusive,
104       C toElement, boolean toInclusive);
105 
106   /*@Override*/ abstract ContiguousSet<C> tailSetImpl(C fromElement, boolean inclusive);
107 
108   /**
109    * Returns the set of values that are contained in both this set and the other.
110    *
111    * <p>This method should always be used instead of
112    * {@link Sets#intersection} for {@link ContiguousSet} instances.
113    */
114   public abstract ContiguousSet<C> intersection(ContiguousSet<C> other);
115 
116   /**
117    * Returns a range, closed on both ends, whose endpoints are the minimum and maximum values
118    * contained in this set.  This is equivalent to {@code range(CLOSED, CLOSED)}.
119    *
120    * @throws NoSuchElementException if this set is empty
121    */
122   public abstract Range<C> range();
123 
124   /**
125    * Returns the minimal range with the given boundary types for which all values in this set are
126    * {@linkplain Range#contains(Comparable) contained} within the range.
127    *
128    * <p>Note that this method will return ranges with unbounded endpoints if {@link BoundType#OPEN}
129    * is requested for a domain minimum or maximum.  For example, if {@code set} was created from the
130    * range {@code [1..Integer.MAX_VALUE]} then {@code set.range(CLOSED, OPEN)} must return
131    * {@code [1..∞)}.
132    *
133    * @throws NoSuchElementException if this set is empty
134    */
135   public abstract Range<C> range(BoundType lowerBoundType, BoundType upperBoundType);
136 
137   /** Returns a short-hand representation of the contents such as {@code "[1..100]"}. */
138   @Override public String toString() {
139     return range().toString();
140   }
141 
142   /**
143    * Not supported. {@code ContiguousSet} instances are constructed with {@link #create}. This
144    * method exists only to hide {@link ImmutableSet#builder} from consumers of {@code
145    * ContiguousSet}.
146    *
147    * @throws UnsupportedOperationException always
148    * @deprecated Use {@link #create}.
149    */
150   @Deprecated public static <E> ImmutableSortedSet.Builder<E> builder() {
151     throw new UnsupportedOperationException();
152   }
153 }
154